var base_url = "http://localhost/digitalboard/";

/* request pollNewData */
function ApplicationController() {
	this.POLL_INTERVAL = 5000;
		
	this.requestPoll();
}

ApplicationController.prototype.requestPoll = function () {
	clearTimeout( this.pollTimeout );
	var self = this;
	this.pollTimeout = setTimeout( function() { self.poll() }, self.POLL_INTERVAL );
}

ApplicationController.prototype.poll = function () {
	
	var url = base_url+"CommHub/poll_new_data";
	var data = {"last_update_time": lastUpdateTime,
				"page_id": pageId,
				"file_id": fileId
				}
					
	$.ajax({
		type: 'POST',
		url: url,
		data:data,
		success: this.getRequestSuccessFunctionReqData(),
		error: this.getRequestErrorFunctionReqData()
	});		
}
function getCanvasObjectById(objId)
{
	var children = layer.getChildren();
	for(var i=0;i<children.length;i++)
	{
		if(children[i].attrs.objectId == objId)
		{	
			return children[i];
		}
	}
	return false;
}
function makeObjectFromBlueprint(blueprint)
{
}
ApplicationController.prototype.getRequestSuccessFunctionReqData = function() {
	var self = this;
	return function( data, textStatus, jqXHR ) {		
		
		var obj = JSON.parse(data);//parse json
		console.log(obj.content);
		for(var i=0;i<obj.content.length;i++)
		{
			var newContent = obj.content[i];
			//validate position
				var existingObject = getCanvasObjectById(newContent.id);
				if(existingObject)
				{
					existingObject.setPosition(parseInt(newContent.posx),parseInt(newContent.posy));
					existingObject.setSize(parseInt(newContent.width),parseInt(newContent.height));
				}
				else
				{
					var imageObj = new Image();
		
					imageObj.onload = function() {
					
						if(isNaN(newContent.x)){newContent.x = 0;}
						if(isNaN(newContent.y)){newContent.y = 0;}
						var urlImage = new Kinetic.Image({
						  x: newContent.posx,
						  y: newContent.posy,
						  image: imageObj,
						  width: newContent.width,
						  height: newContent.height
						});

						
						var newImage = createImageFromImageObject(obj.w,obj.h,urlImage,newContent.id,obj.x,obj.y);
						layer.add(newImage);
						layer.draw();
						
						
						newImage.on('dragend', function() {
							var position = newImage.getPosition();
							var dimension = newImage.getSize();
						
							var objectJson = {"id": newImage.attrs.objectId, "posy": position.y, "posx": position.x, "height": dimension.height, "width": dimension.width };
							console.log(position.y);
							var jsonString = JSON.stringify(objectJson);
							var url = base_url+"CommHub/update_object_property";
							var newData = {"file_id": fileId,
											"page_id": pageId,
											"object_json":jsonString,
											}
							
							$.ajax({
								type: 'POST',
								url: url,
								data:newData,
								// success: this.getRequestSuccessFunctionAllData(),
								// error: this.getRequestErrorFunctionAllData()
							});
						});

				
		  };
					imageObj.src = base_url+newContent.image_url;
				}
			
			console.log(existingObject);
		}
		layer.draw();
		lastUpdateTime = obj.last_update;
		// console.log(lastUpdateTime);
		self.requestPoll();
	}
}

ApplicationController.prototype.getRequestErrorFunctionReqData = function( errorThrown ) {
	var self = this;
	return function() {
		if ( console && console.log ) {
			console.log( "ERROR: " + errorThrown );
		}

		self.requestPoll();
	}
}

/* end request pollNewData */
function StoreImage(image,filepath,callbackObject)
{
	var url = base_url+"CommHub/store_image/";
	var allData = {
					"image_data":image,
					"filepath":filepath
					};
	$.ajax({
		type: 'POST',
		url: url,
		data:allData,
		success: callbackObject.uploadSuccess(),
		error: callbackObject.uploadFail()
	});
}
function AddObject(image,filepath,posx,posy,callbackObject)
{
	var url = base_url+"CommHub/add_object/";
	var allData = {
					"image_data":image,
					"file_id":fileId,
					"page_id":pageId,
					"id": (new Date).getTime(),
					"filepath":filepath,
					"posx":posx,
					"posy":posy
					};
	$.ajax({
		type: 'POST',
		url: url,
		data:allData,
		success: callbackObject.uploadSuccess(),
		error: callbackObject.uploadFail()
	});
}
/* request getFileData */

function RequestAllData() {
	var url = base_url+"CommHub/get_file_data";
	var allData = {"file_id": fileId}
	
	$.ajax({
		type: 'POST',
		url: url,
		data:allData,
		success: this.getRequestSuccessFunctionAllData(),
		error: this.getRequestErrorFunctionAllData()
	});
}
function loadDrawingObject(drawingArray,index)
{
	//var i;
	//for(i=0;i<drawingArray.length;i++){
		var imageObj= new Image();
		var imageObjData = drawingArray[index];
		imageObj.onload = function() {
			console.log("Image Object");
			console.log(imageObj);
			var newImage = createImage(parseInt(imageObjData.px),parseInt(imageObjData.py),parseInt(imageObjData.w),parseInt(imageObjData.h),imageObj,imageObjData.id);
			console.log(newImage);
			layer.add(newImage);
			layer.draw();
			
			newImage.on('dragend', function() {
				var position = newImage.getPosition();
				var dimension = newImage.getSize();
						
				var image = newImage.getChildren()[0];
				console.log(newImage);
				var objectJson = {"id": newImage.attrs.objectId, "posy": position.y, "posx": position.x, "height": newImage.attrs.height, "width": newImage.attrs.width };
				var json = JSON.stringify(objectJson);
					
				var url = base_url+"CommHub/update_object_property";
				var newData = {"file_id": fileId,
								"page_id": pageId,
								"object_json":json,
								}
				
				$.ajax({
					type: 'POST',
					url: url,
					data:newData
					// success: this.getRequestSuccessFunctionAllData(),
					// error: this.getRequestErrorFunctionAllData()
				});
			});
			if(index+1<drawingArray.length)
				loadDrawingObject(drawingArray,index+1);
		};
		imageObj.src = base_url+imageObjData.src;					  
	//}
}
RequestAllData.prototype.getRequestSuccessFunctionAllData = function() {
	var self = this;
	return function( data, textStatus, jqXHR ) {		
		
		    $("#loading_indicator").modal('hide');  
			
			var obj = JSON.parse(data);//parse json
		    if (window.DOMParser)//parse xml
			{
			  parser=new DOMParser();
			  xmlDoc=parser.parseFromString( obj.content,"text/xml");
			}
			else // Internet Explorer
			{
			  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			  xmlDoc.async=false;
			  xmlDoc.loadXML( obj.content); 
			}
			 
			 var pages=xmlDoc.getElementsByTagName("pages")[0].childNodes;
			 for (var i=0;i<pages.length;i++)
			 {
				if(pages[i].nodeName=="page")
				{
					var drawingObjects = pages[i].childNodes;
					var imageObjs =new Array();
					for(var j=0;j<drawingObjects.length;j++)
					{

						if(drawingObjects[j].nodeName=="drawing_object")
						{
							var drawingAttr = drawingObjects[j].attributes;
							var drawObject = {px:0,py:0,w:0,h:0,src:0,id:0};
							
							for(var k=0;k<drawingAttr.length;k++)
							{
								if(drawingAttr[k].nodeName=="id"){
									drawObject.id = drawingAttr[k].nodeValue;
								}else if(drawingAttr[k].nodeName=="posx"){
									drawObject.px = drawingAttr[k].nodeValue;
								}else if(drawingAttr[k].nodeName=="posy"){
									drawObject.py = drawingAttr[k].nodeValue;
								}else if(drawingAttr[k].nodeName=="width"){
									drawObject.w = drawingAttr[k].nodeValue;
								}else if(drawingAttr[k].nodeName=="height"){
									drawObject.h = drawingAttr[k].nodeValue;
								}else if(drawingAttr[k].nodeName=="image_url"){
									drawObject.src = drawingAttr[k].nodeValue;
									
								}
							}
							imageObjs.push(drawObject);
							
						}
					}
					if(imageObjs.length>0)
					loadDrawingObject(imageObjs,0);
					//loadImageObjectToStage(imageObjs,0);
				}
			 }
			 console.log(xmlDoc);
	}
}

//Request All Data
function loadImageObjectToStage(imageObjs,offset){
	console.log(imageObjs);
	
	createImageFromDataSource();
}

RequestAllData.prototype.getRequestErrorFunctionAllData = function( errorThrown ) {
	var self = this;
	return function() {
		if ( console && console.log ) {
			console.log( "ERROR: " + errorThrown );
		}
	}
}

/* end request getFileData */